// web-scoket.js
import { Notification } from "element-ui";

// WebSocket 地址
let webSocketUrl = 'ws://' + getWeburl() + ':8090/ws/webSocket/';

// 心跳间隔时间（毫秒）
const HEARTBEAT_INTERVAL = 30000; // 30秒
// 重连间隔时间（毫秒）
const RECONNECT_INTERVAL = 5000; // 5秒

// 接收 WebSocket 数据
export function webSocketHandler(empName) {
  const wsuri = webSocketUrl + empName;
  console.log(wsuri);
  let ws = new WebSocket(wsuri);
  let heartbeatIntervalId = null;
  let reconnectIntervalId = null;

  ws.onopen = function (event) {
    console.log("已经打开连接");
    // 清除重连定时器
    clearInterval(reconnectIntervalId);
    // 启动心跳定时器
    heartbeatIntervalId = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'heartbeat' }));
      }
    }, HEARTBEAT_INTERVAL);
  };

  ws.onmessage = function (event) {
    var messageBody = JSON.parse(event.data);
    if (messageBody.type === 'heartbeat') {
      // 心跳消息，不需要处理
      return;
    }
    Notification({
      title: "通知",
      dangerouslyUseHTMLString: true,
      duration: 0,
      offset: 40,
      type: 'success',
      position: 'bottom-right',
      message: messageBody.noticeContent, // 自定义HTML模板
      onClick: function () {
        // 处理点击事件
        // if(messageBody.type === '1'){
        //   let id = messageBody.custId;
        //   const params = { id: id, queryParams: JSON.stringify(this.queryParams), pageNum: this.queryParams.pageNum, form: this.form, routePath: this.$route.path, custOpType: this.$route.query.custOpType };
        //   this.$tab.openPage(`修改客户[${custName}]`, `/crmsys/custedit/info/${id}`, params);
        // }
      },
    });

    document.getElementById('audio').play();
  };

  ws.onclose = function (event) {
    console.log("关闭链接");
    // 清除心跳定时器
    clearInterval(heartbeatIntervalId);
    // 启动重连定时器
    reconnectIntervalId = setInterval(() => {
      console.log("尝试重新连接...");
      webSocketHandler(empName);
      clearInterval(reconnectIntervalId); // 重新连接成功后清除定时器
    }, RECONNECT_INTERVAL);
  };

  ws.onerror = function (event) {
    console.error("WebSocket 错误:", event);
  };
}

// 获取网址
export function getWeburl() {
  const ipAddress = window.location.href;
  const urlObject = new URL(ipAddress);
  return urlObject.hostname;
}